/**
 * 人员管理
 */

<template>
  <div class="courseBox">
    <div class="courseBoxTop">
      <div class="courseBoxTopSearch">
        <div class="courseName">
          <span>人员名称：</span>
          <el-input
            v-model="searchForm.nickName"
            placeholder="请输入人员名称"
          />
        </div>
        <div class="version">
          <span>部门：</span>
          <el-select
            v-model="searchForm.organizationId"
            placeholder="请选择部门"
          >
            <el-option
              :label="item.organizationName"
              :value="item.organizationId"
              v-for="(item, index) in majorList"
              :key="index"
            ></el-option>
          </el-select>
        </div>
        <div class="courseName">
          <span>手机号：</span>
          <el-input
            v-model="searchForm.phoneNumber"
            placeholder="请输入手机号"
          />
        </div>

        <div class="searchAndReset">
          <el-button class="searchBtn" @click="searchInput">
            <i class="el-icon-search"></i>
            <span>搜索</span>
          </el-button>
          <el-button class="resetBtn" @click="refreshInput">
            <i class="el-icon-refresh"></i>
            <span>重置</span>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 管理列表 -->
    <div class="courseBoxBottom">
      <div class="bottomHeader">
        <span class="title">管理列表</span>
        <div class="bottomHeaderBtn">
          <el-button class="addBtn" @click="openAddPersonnel">
            <i class="el-icon-plus"></i>
            <span>新增</span>
          </el-button>
          <el-button class="delBtn" @click="batchDelPersonnel">
            <i class="el-icon-close"></i>
            <span>批量删除</span>
          </el-button>
          <el-button class="toLeadBtn" @click.stop="setIsMaskOpen">
            <i class="icon iconfont icon-daoru"></i>
            <span>批量导入</span>

            <!-- 弹框 -->
            <div
              class="toLeadBtnMask"
              v-if="isMask"
              @mouseenter="setIsMaskOpen"
              @mouseleave="setIsMaskClose"
            >
              <span class="sanjiao"></span>
              <div class="ul">
                <el-upload
                  class="upload-demo"
                  name="file"
                  action="action"
                  :http-request="handlePreview"
                >
                  <div class="li">
                    <i></i>
                    <span size="small" class="importPersonnel">
                      导入教师名单
                    </span>
                  </div>
                </el-upload>

                <div class="li" @click="exportPersonnel">
                  <i></i>
                  <span>下载导入模板</span>
                </div>
              </div>
            </div>
          </el-button>

          <el-button class="exportBtn" @click="exportPersonnel">
            <i class="icon iconfont icon-daochu"></i>
            <span>导出数据</span>
          </el-button>
        </div>
      </div>

      <!-- 表格 -->
      <div class="bottomMian">
        <el-table
          ref="multipleTable"
          :data="courseList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50"> </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            width="50"
          ></el-table-column>
          <el-table-column prop="userName" label="用户账号"> </el-table-column>
          <el-table-column prop="nickName" label="用户名称"></el-table-column>
          <el-table-column
            prop="organizationName"
            label="部门"
          ></el-table-column>
          <el-table-column prop="phoneNumber" label="手机号"></el-table-column>

          <el-table-column
            prop="createTime"
            label="创建时间"
            min-width="150"
          ></el-table-column>

          <el-table-column label="启用状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#C2C2C2"
                @change="updateIsUsing(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="action" label="操作">
            <template slot-scope="scope">
              <span
                class="icon iconfont icon-bianji"
                @click="editPersonnel(scope.row)"
              ></span>
              <span
                class="icon iconfont icon-shanchu"
                @click="delPersonnel(scope.row.id)"
              ></span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination" v-if="courseList.length > 0">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="10"
            prev-text="上一页"
            next-text="下一页"
            layout=" prev, pager, next"
            :total="total"
          >
          </el-pagination>
          <div class="jumper">
            跳到第
            <input type="text" ref="currentPage" value="1" />
            页
          </div>
          <button class="submit" @click="goPage">确定</button>
        </div>
      </div>
    </div>

    <!-- 新增人员 -->
    <div class="dialog">
      <el-dialog
        :title="isEdit ? '编辑人员' : '添加人员'"
        :visible.sync="dialogFormVisible"
        center
      >
        <el-form :model="form" ref="courseForm" :rules="rules">
          <el-form-item label="人员账号:" :label-width="formLabelWidth">
            <el-input
              v-model="form.userName"
              autocomplete="off"
              placeholder="请输入人员账号"
              style="width: 280px"
            ></el-input>
          </el-form-item>
          <el-form-item label="人员名称:" :label-width="formLabelWidth">
            <el-input
              v-model="form.nickName"
              autocomplete="off"
              placeholder="请输入人员名称"
              style="width: 280px"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门:" :label-width="formLabelWidth">
            <el-select
              v-model="form.organizationId"
              placeholder="请选择部门"
              style="width: 280px"
              @change="setPersonnelTypeName"
            >
              <el-option
                :label="item.organizationName"
                :value="item.organizationId"
                v-for="(item, index) in majorList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="手机号:"
            :label-width="formLabelWidth"
            prop="phoneNumber"
          >
            <el-input
              v-model="form.phoneNumber"
              autocomplete="off"
              placeholder="请输入手机号"
              style="width: 280px"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAddPersonnel">取 消</el-button>
          <el-button type="primary" @click="confirmAddPersonnel"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import "@/styles/picture.scss";
import { _debounce } from "@/utils/debounce";

import {
  exportApi,
  importApi,
  getPersonnelListApi,
  addPersonnelApi,
  delPersonnelApi,
  updatePersonnelApi,
  getOrganizationListApi,
} from "@/api/selfStudy/personnel";
export default {
  data() {
    return {
      courseList: [],
      majorList: [],
      total: 0,
      multipleSelection: [],
      currentPage: 1,
      isMask: false,
      pageSize: 10,
      dialogFormVisible: false,
      searchForm: {
        phoneNumber: "",
        nickName: "",
        organizationId: "",
      },
      form: {
        id: "",
        phoneNumber: "",
        userName: "",
        nickName: "",
        organizationId: "",
      },
      formLabelWidth: "100px",
      isEdit: false,
      filename: "人员管理表",
      rules: {
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: function (rule, value, callback) {
              if (/^1[3-9]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
    };
  },

  mounted() {
    // 获取人员列表
    this.getPersonnelList({
      pageNum: this.currentPage,
      pageSize: this.pageSize,
    });

    // 获取机构列表
    getOrganizationListApi().then((res) => {
      this.majorList = res.data.filter((item) => {
        return item.status == "0";
      });
    });
  },

  methods: {
    setPersonnelTypeName(data) {
      this.form.courseTypeName = data.split(",")[1];
      this.form.courseTypeId = data.split(",")[0];
    },

    //  获取人员列表 / 搜索
    getPersonnelList(data) {
      getPersonnelListApi(data).then((result) => {
        if (result.code === 200) {
          this.courseList = result.rows.map((item) => {
            return {
              ...item,
              status: item.status == "0" ? true : false,
            };
          });
          this.total = result.total;
        }
      });
    },

    // 搜索
    searchInput: _debounce(function () {
      this.getPersonnelList({
        ...this.searchForm,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    }, 200),

    // 重置
    refreshInput: _debounce(function () {
      this.searchForm = {
        phoneNumber: "",
        nickName: "",
        organizationId: "",
      };
      this.getPersonnelList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    }, 200),

    // 新增人员
    openAddPersonnel() {
      this.isEdit = false;
      this.dialogFormVisible = true;
      this.$refs["courseForm"].resetFields();
      this.form = {
        id: "",
        phoneNumber: "",
        userName: "",
        nickName: "",
        organizationId: "",
      };
    },

    // 修改
    editPersonnel(data) {
      this.isEdit = true;
      this.dialogFormVisible = true;
      let { id, phoneNumber, userName, nickName, organizationId } = data;
      this.form = {
        id,
        phoneNumber,
        userName,
        nickName,
        organizationId,
      };
    },

    // 取消新增
    closeAddPersonnel() {
      this.dialogFormVisible = false;
    },

    // 确定新增 / 编辑
    confirmAddPersonnel: _debounce(function () {
      if (this.isEdit) {
        updatePersonnelApi(this.form).then((res) => {
          if (res.code === 200) {
            this.$message.success("修改成功!");
            this.dialogFormVisible = false;
            this.getPersonnelList({
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            });
          } else {
            this.$message.error("修改失败!");
          }
        });
      } else {
        addPersonnelApi({ ...this.form, status: "0" }).then((res) => {
          if (res.code === 200) {
            this.$message.success("添加成功!");
            this.dialogFormVisible = false;
            this.getPersonnelList({
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            });
          } else {
            this.$message.error("添加失败!");
          }
        });
      }
    }, 200),

    // 删除
    delPersonnel(ids) {
      this.$confirm("此操作将删除该人员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delPersonnelApi({ ids }).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功!");
              this.getPersonnelList({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
              });
            } else {
              this.$message.error("删除失败!");
            }
          });
        })
        .catch(() => {});
    },

    // 批量删除
    batchDelPersonnel() {
      if (this.multipleSelection.length) {
        let data = [...this.multipleSelection].map((item) => {
          return "" + item.id;
        });
        this.$confirm("此操作将删除已选择的人员, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delPersonnelApi({ ids: data.join(",") }).then((res) => {
              if (res.code === 200) {
                this.$message.success("删除成功!");
                this.getPersonnelList({
                  pageNum: this.currentPage,
                  pageSize: this.pageSize,
                });
              } else {
                this.$message.error("删除失败!");
              }
            });
          })
          .catch(() => {});
      } else {
        this.$message.error("请选择要删除的人员！");
      }
    },

    // 修改启用状态
    updateIsUsing(data) {
      let { id, status } = data;
      updatePersonnelApi({
        id,
        status: status ? "0" : "1",
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("修改成功!");
          this.dialogFormVisible = false;
          this.getPersonnelList({
            ...this.searchForm,
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          });
        } else {
          this.$message.error("修改失败!");
        }
      });
    },

    // 打开导入弹框
    setIsMaskOpen() {
      this.isMask = true;
    },

    // 关闭导入弹框
    setIsMaskClose() {
      this.isMask = false;
    },

    // 导出
    exportPersonnel() {
      this.$confirm("是否导出全部数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          exportApi().then((res) => {
            if (!res) return;
            const blob = new Blob([res], {
              type: "application/vnd.ms-excel",
            }); // 构造一个blob对象来处理数据，并设置文件类型
            if (window.navigator.msSaveOrOpenBlob) {
              //兼容IE10
              navigator.msSaveBlob(blob, this.filename);
            } else {
              const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
              const a = document.createElement("a"); //创建a标签
              a.style.display = "none";
              a.href = href; // 指定下载链接
              a.download = this.filename; //指定下载文件名
              a.click(); //触发下载
              URL.revokeObjectURL(a.href); //释放URL对象
            }
          });
        })
        .catch(() => {});
    },

    // 导入上传
    handlePreview(files) {
      let formData = new FormData();
      formData.append("file", files.file);
      importApi(formData).then((res) => {
        if (res.code === 200) {
          this.$message.success("导入成功！");
          this.getPersonnelList({
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          });
        }
      });
    },

    // 选择 / 全选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 更改当前页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPersonnelList({
        ...this.searchForm,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    },

    // 跳转当前页
    goPage() {
      let { value } = this.$refs.currentPage;
      this.currentPage = Number(value);
      this.getPersonnelList({
        ...this.searchForm,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.courseBoxTopSearch {
  ::v-deep .el-input__inner {
    height: 36px;
    line-height: 36px;
  }
}

.action {
  cursor: pointer;
}

.dialog {
  ::v-deep .el-dialog {
    max-width: 750px;
    min-width: 500px;
    border-radius: 10px;
    background-color: #f9f9f9;
  }

  ::v-deep .el-dialog__header {
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    background-color: #4895db;
    padding: 0;
    border-radius: 10px 10px 0 0;

    span {
      font-size: 16px;
      color: #fff;
    }
  }

  ::v-deep .el-dialog__headerbtn {
    top: 15px;
  }

  ::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #fff;
    font-size: 18px;
  }

  ::v-deep .el-dialog--center .el-dialog__body {
    text-align: initial;
    display: flex;
    justify-content: center;
  }

  ::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }

  ::v-deep .el-form-item__content {
    width: 300px;
  }

  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }

  ::v-deep .el-dialog__footer {
    padding: 10px 20px 50px;
  }

  ::v-deep .el-button--default {
    width: 130px;
    border-radius: 20px;
    background-color: #f0f0f0;
    color: #aaaaaa;
    border: none;
  }

  ::v-deep .el-button + .el-button {
    width: 130px;
    border-radius: 20px;
    margin-left: 50px;
    background-color: #4895db;
    border-color: #4895db;
  }
}
</style>